import 'package:flutter/material.dart';
import 'package:mvvm_demo/mvvm/list_data.dart';
import 'package:mvvm_demo/mvvm/mutable_live_data.dart';
import 'package:mvvm_demo/mvvm/top_data.dart';
import 'package:mvvm_demo/mvvm/view_model.dart';
import 'package:provider/provider.dart';

class LoginMvvm extends StatefulWidget {
  const LoginMvvm({Key? key}) : super(key: key);

  @override
  _LoginMvvmState createState() {
    return _LoginMvvmState();
  }
}

class _LoginMvvmState extends State<LoginMvvm> {
  late final ViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = ViewModel();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => _viewModel.topData),
        ChangeNotifierProvider(create: (_) => _viewModel.listData),
        ChangeNotifierProvider(create: (_) => _viewModel.text),
      ],
      child: Center(
        child: Column(
          children: [
            Consumer2<TopData,MutableLiveData<String>>(builder: (_, topData,liveData, child) {
              return Column(
                children: [
                  Text(topData.name),
                  Text(topData.age),
                  Text(liveData.value),
                ],
              );
            }),
            Expanded(
              child: Consumer<ListData>(builder: (_, listData, child) {
                return ListView.builder(
                    itemCount: listData.list.length,
                    itemExtent: 30,
                    itemBuilder: (context, index) {
                      return Text(listData.list[index].toString());
                    });
              }),
              flex: 1,
            ),
            ElevatedButton(
                onPressed: () {
                  _viewModel.refreshData();
                },
                child: Text("修改头部")),
            ElevatedButton(
                onPressed: () {
                  _viewModel.refreshList();
                },
                child: Text("修改列表")),
            ElevatedButton(
                onPressed: () {
                  _viewModel.refreshData();
                  _viewModel.refreshList();
                },
                child: Text("修改头部和列表")),
          ],
        ),
      ),
    );
  }
}
